<template>
    <div style="background-color: white">
        <a-row style="padding: 10px">
            <a-range-picker
                v-model="searchDateRange"
                :ranges="{ '今天': [moment().startOf('day'), moment()], '本月': [moment().startOf('month'), moment()] }"
                show-time size="default"
                style="margin-right: 6px"/>

            <a-select :filter-option="filterOption"
                      allowClear
                      placeholder="请选择工地"
                      show-search
                      style="width: 116px;margin:0 4px 0 4px;"
                      @change="(value)=>{selectIndex=value;}">
                <a-select-option v-for="(item,index) in buildingSites" :key="index">
                    {{ item }}
                </a-select-option>
            </a-select>
            <a-select :filter-option="filterOption"
                      allowClear
                      placeholder="请选择任务状态"
                      show-search
                      style="width: 150px;margin:0 4px 0 4px;"
                      @change="(value)=>{selectStatusIndex=value;}">
                <a-select-option v-for="(item,index) in ['未处理','已完成','已过期']" :key="index">
                    {{ item }}
                </a-select-option>
            </a-select>
            <a-select :filter-option="filterOption"
                      :defaultValue="0"
                      placeholder="请选择角色"
                      show-search
                      style="width: 150px;margin:0 4px 0 4px;"
                      @change="(value)=>{selectRoleIndex=value;}">
                <a-select-option v-for="(item,index) in roles" :key="index">
                    {{ item }}
                </a-select-option>
            </a-select>


            <a-button style="margin-left: 6px;" @click="getTaskList(page,pageSize)" type="primary">查询</a-button>
            <a-button @click="addTaskModalVisible=true" style="margin-left: 6px;" type="primary">新建任务</a-button>
        </a-row>
        <a-table :columns="columns" :data-source="data" rowKey="id" :pagination="false" bordered>
            <a slot="state" slot-scope="state">
                <span v-if="state == 0">未处理</span>
                <span v-if="state == 1">已完成</span>
                <span v-if="state == 2">已过期</span>
            </a>
            <a slot="qx" slot-scope="qx">
                <span>{{ roles[qx - 1] }}</span>
            </a>
            <a slot="purl" slot-scope="purlArray">
                <img @click="() => {previewImageURl= baseUrl + purlArray[0]; previewVisible=true}"
                     style="width: 100px" v-if="purlArray != undefined" :src="baseUrl + purlArray[0]"
                     alt="整改前的图片">
            </a>
            <a slot="purlEnd" slot-scope="purlEndArray">
                <img @click="() => {previewImageURl= baseUrl + purlEndArray[0]; previewVisible=true}"
                     style="width: 100px" v-if="purlEndArray != undefined" :src="baseUrl + purlEndArray[0]"
                     alt="整改后的图片">
            </a>
            <a slot="action" slot-scope="item">
                <a-button @click="showTaskDetail(item)">详情</a-button>
            </a>
        </a-table>

        <a-pagination v-model="current" :default-current="2"
                      :pageSize="pageSize"
                      :pageSizeOptions="['5','10', '20', '30', '40']"
                      :showSizeChanger="true"
                      :showTotal="total => `共 ${total} 条`"
                      :total="total"
                      show-quick-jumper
                      @change="onChange" @showSizeChange="onShowSizeChange"/>

        <!--        任务详情弹窗-->
        <a-modal
            title="任务详情"
            :visible="visible"
            @ok="visible = false"
            @cancel="visible = false"
            :footer="null"
        >
            <div v-if="modalData.purlArray != undefined">
                <a-row>
                    <a-col span="12">
                        <div v-for="(item, index) in modalData.purlArray"
                             :key="index">
                            <p>整改项：{{ cause[modalData.cyArray[index] - 1] }}</p>
                            <p>整改前的图片</p>
                            <img @click="() => {previewImageURl= baseUrl + item; previewVisible=true}"
                                 style="width: 100px;height: 100px"
                                 :src="baseUrl + item"
                                 alt="整改前的图片"/>

                            <hr>
                        </div>

                    </a-col>
                    <a-col span="12">
                        <div v-for="(item, index) in modalData.purlEndArray"
                             :key="index">
                            <p>&nbsp;</p>
                            <p>整改后的图片</p>
                            <img style="width: 100px;height: 100px"
                                 @click="() => {previewImageURl= baseUrl + item; previewVisible=true}"
                                 :src="baseUrl + item"
                                 alt="整改后的图片"/>

                            <hr>
                        </div>

                    </a-col>
                </a-row>


            </div>
            <div v-if="modalData.bz != null && modalData.bz != ''">
                <p>处理人提交的其他污染原因:</p>
                <p>{{ modalData.bz }}</p>
            </div>
        </a-modal>


        <!--        图片预览弹窗-->
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImageURl"/>
        </a-modal>


        <!--        手动添加任务弹窗-->
        <a-modal title="手动调度"
                 :footer="null"
                 :visible="addTaskModalVisible"
                 @cancel="addTaskModalVisible = false">

            <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
                <a-form-item label="处理时间">
                    <a-input suffix="分钟"
                             disabled
                             v-decorator="['time', { rules: [{ required: true, message: '请输入你希望多少分钟内处理！' }],initialValue: 120 }]"
                    />
                </a-form-item>
                <a-form-item label="角色">
                    <a-select :filter-option="filterOption"
                              v-decorator="[ 'qx',
                              { rules: [{ required: true, message: '请选择角色!' }] },
                               ]"
                              :defaultValue="0"
                              placeholder="请选择角色"
                              show-search
                              style="width: 150px;margin:0 4px 0 4px;"
                    >
                        <a-select-option v-for="(item,index) in roles" :key="index">
                            {{ item }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="工地">
                    <a-select :filter-option="filterOption"
                              v-decorator="[ 'gdname',
                              { rules: [{ required: true, message: '请选择需要处理的工地!' }] },
                               ]"
                              allowClear
                              placeholder="请选择工地"
                              show-search
                              style="width: 116px;margin:0 4px 0 4px;"
                    >
                        <a-select-option v-for="(item,index) in buildingSites" :key="index">
                            {{ item }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="描述">
                    <a-textarea v-decorator="[ 'name',
                              { rules: [{ required: true, message: '输入一些问题的描述!' }] },
                               ]"
                                placeholder="输入一些问题的描述" :rows="4"/>

                </a-form-item>
                <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                    <a-button :loading="loading" type="primary" html-type="submit">
                        添加
                    </a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
<script lang="ts">

import {getNodeFromTreeByLevel} from "../../utils/util.js";
import {METHOD, request, RESPONSE} from "../../utils/request.js"
import moment from "moment";
import axios from "axios";


const columns = [
    {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
    },
    {
        title: '工地',
        dataIndex: 'gdname',
        key: 'gdname',
    },
    {
        title: '描述',
        dataIndex: 'name',
        width: 150,
        key: 'name',
    },
    {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        scopedSlots: {customRender: 'state'},
    },
    {
        title: '开始时间',
        dataIndex: 'addtime',
        key: 'addtime',
    },
    {
        title: '结束时间',
        dataIndex: 'endime',
        key: 'endime',
    },
    {
        title: '整改前的图片',
        dataIndex: 'purlArray',
        key: 'purl',
        scopedSlots: {customRender: 'purl'},
    },
    {
        title: '整改前的图片',
        dataIndex: 'purlEndArray',
        key: 'purlEnd',
        scopedSlots: {customRender: 'purlEnd'},
    },
    {
        title: '处理人电话',
        dataIndex: 'userid',
        key: 'userid',
        scopedSlots: {customRender: 'userid'},
    },
    {
        title: '处理人角色',
        dataIndex: 'qx',
        key: 'qx',
        scopedSlots: {customRender: 'qx'},
    },
    {
        title: '操作',
        key: 'action',
        scopedSlots: {customRender: 'action'},
    }
];

const cause = [
    "1.1 施工现场未围挡",
    "1.2 工地物料未覆盖堆放",
    "1.3 车辆未冲洗",
    "1.4 未湿法作业",
    "1.5 运土车辆未封闭",
    "1.6 在线扬尘监控屏未安装",
]

// interface RequestTaskParam {
//     qx: string,    // 权限等级
//     userid: string,  // 用户id
//     state: string,  // 任务状态
//     startime: string,  // 开始时间
//     endtime: string,  // 结束时间
//     gid: string  // 工地id
// }


export default {
    data() {
        return {
            current: 1,  // 当前页码
            pageSize: 5, // 每页数量
            total: 0,   // 一共的机器数量
            loading: false,
            userID: null,
            form: this.$form.createForm(this, {name: 'coordinated'}),
            moment,
            searchDateRange: [],
            selectStatusIndex: null,
            selectRoleIndex: 0,
            selectIndex: null,
            buildingSites: [],
            buildingSiteKeys: [],   // 工地key列表
            previewVisible: false,
            addTaskModalVisible: false,
            previewImageURl: "",
            baseUrl: axios.defaults.baseURL,
            roles: ["施工方", "街道办", "住建局", "环保局"],
            visible: false,
            data: [],
            buildSitesdata: [],
            modalData: {
                bz: "",
                purlArray: [],
                purlEndArray: [],
                cyArray: []
            },  // 弹窗展示的数据
            columns,
            cause,
            purlArray: [],  // 整改前的图片列表
            purlEndArray: [],  // 整改后的图片列表
        };
    },
    beforeMount() {
        this.getTaskList(1, 5)


        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;


        request("/areas/getAreas?id=" + this.userID, METHOD.GET, null, null).then(result => {
            if (result.data.code === 1) {

                getNodeFromTreeByLevel(result.data.data, 3, this.buildSitesdata);

                this.buildSitesdata.forEach(item => {
                    this.buildingSites.push(item.title)
                    this.buildingSiteKeys.push(item.key)
                })

                console.log(this.buildingSites)

                this.$message.success('成功');
            }
        })
    },
    methods: {
        onChange(page, pageSize) {
            this.getTaskList(page, pageSize);
        },
        onShowSizeChange(page, pageSize) {
            this.getTaskList(page, pageSize);
        },
        handleSubmit(e) {
            e.preventDefault();
            this.loading = true;
            this.form.validateFields((err, values) => {
                if (!err) {
                    console.log('Received values of form: ', values);

                    this.manualAddTask(values);
                } else {
                    this.loading = false;
                }
            });
        },
        manualAddTask(data) {
            var manualAddTaskRequestBody = {
                time: 0,
                qx: 0,
                gdname: "",
                gdid: 0,
                acid: 0,
                name: ""
            };

            manualAddTaskRequestBody.acid = this.userID;
            manualAddTaskRequestBody.time = data.time;
            manualAddTaskRequestBody.name = data.name;
            manualAddTaskRequestBody.qx = data.qx + 1;
            manualAddTaskRequestBody.gdname = this.buildingSites[data.gdname];
            manualAddTaskRequestBody.gdid = this.buildingSiteKeys[data.gdname];
            console.log(this.buildingSiteKeys[data.gdname]);
            console.log(manualAddTaskRequestBody);

            request("/appoder/addOder", METHOD.POST, manualAddTaskRequestBody, null).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.$message.success('添加任务成功');

                    this.addTaskModalVisible = false;
                    this.form.resetFields();
                } else {
                    this.$message.error(`添加任务失败${res.data.msg}`);
                }

                this.loading = false;
            })
        },
        filterOption(input, option) {
            return (
                // 过滤忽略大小写
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        showTaskDetail(item) {
            this.modalData.purlArray = item.purlArray;
            this.modalData.purlEndArray = item.purlEndArray;
            this.modalData.cyArray = item.cyArray;
            this.modalData.bz = item.bz;
            this.visible = true;

            console.log(item);
        },
        getTaskList(page = 1, pageSize = 5) {
            const data = {
                page: page,
                pageSize: pageSize,
                qx: this.selectRoleIndex + 1,
                userid: '4',
                state: this.selectStatusIndex,
                startime: this.searchDateRange.length === 2 ? this.searchDateRange[0].format("yyyy-MM-DD HH:mm:ss") : null,
                endtime: this.searchDateRange.length === 2 ? this.searchDateRange[1].format("yyyy-MM-DD HH:mm:ss") : null,
                gid: this.buildingSiteKeys[this.selectIndex],
            };
            request("/appoder/getOder", METHOD.GET, data, null).then(res => {

                console.log(res);
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.data = res.data.data.records;
                    this.total = res.data.data.total;

                    this.data.forEach((item) => {
                        if (item.purl != null && item.purl != "") {
                            item.purlArray = item.purl.split(",");
                            item.purlEndArray = item.purlEnd.split(",");
                            item.cyArray = item.cy.split(",");
                        }

                        console.log(item)
                    })
                }
            })
        }
    }
};
</script>


<style scoped lang="less">

</style>
